﻿#ifndef WRWORKGUIINITTHREADWORKER
#define WRWORKGUIINITTHREADWORKER

#include <QMutex>
#include <QWidget>
#include <QRunnable>
#include <QCoreApplication>
#include "WRWorkGuiInitEvent.h"

//表示工作界面初始线程处理者。
template <class TParams, class TResult> class WRWorkGuiInitThreadWorker : public QRunnable
{
private:
    QMutex m_mutex;
    QWidget* m_owner;
    TParams m_params;
    TResult* m_result;

public:
    //初始化处理者。
    WRWorkGuiInitThreadWorker(QWidget* owner, const TParams& params)
        : m_params(params)
    {
        m_owner = owner;
        m_result = 0;
        setAutoDelete(false);
    }
    //清理当前对象所占用的相关资源。
    ~WRWorkGuiInitThreadWorker()
    {
        //add code here
    }

    //获取目标。
    inline const TParams& params(void) const
    {
        return m_params;
    }
    //获取结果。
    inline TResult* result(void) const
    {
        return m_result;
    }

    //线程池执行方法。
    void run(void)
    {
        if (m_owner)
        {
            m_result = new TResult(m_params);

            m_mutex.lock();
            if (m_owner)
            {
                QCoreApplication::postEvent(m_owner, new WRWorkGuiInitEvent(this));
                m_mutex.unlock();
            }
            else
            {
                m_mutex.unlock();
                delete m_result;
                delete this;
            }
        }
        else
        {
            delete this;
        }
    }

    //停止对象的执行。
    void stop(void)
    {
        QMutexLocker lck(&m_mutex);
        m_owner = 0;
    }
};

#endif // WRWORKGUIINITTHREADWORKER

